package cn.niit.letuseatdemo.interceptor;


import cn.niit.letuseatdemo.entity.domain.User;
import cn.niit.letuseatdemo.entity.vo.response.BaseResponse;
import cn.niit.letuseatdemo.util.H5LoginUtil;
import cn.niit.letuseatdemo.util.RedisUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description: 主要负责对前后端分离项目前端调用后端（/api/**）接口进行拦截

 * @CreateTime: 2022/11/18 10:08
 * @param: null
 * @return: null
 **/
@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisUtil redisUtil;
    /**
     * @Description: 控制器方法执行之前执行

     * @CreateTime: 2022/10/11 8:46
     * @return: boolean：true：放行；false：拒绝
     **/
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        if("OPTIONS".equals(request.getMethod())){  //如果请求方法（requestMethod）是 OPTIONS，则直接放行；
            return true;
        }
        /** 从请求头中获取 token  */
        String token = request.getHeader("auth-token");
        log.info("拦截器 AuthInterceptor.preHandle 获取到的token ： " + token);
        if(!StringUtils.isEmpty(token)){
            User user = (User) redisUtil.get("token-" + token);
            if(null != user){
                H5LoginUtil.setLoginUser(user);
                return true;    //放行；
            }
        }
        log.info("request.getMethod() = "+ request.getMethod());
        response.getWriter().write(JSON.toJSONString(BaseResponse.error("9005", "未登录或登录超时！")));
        response.getWriter().close();
        return false;   //拒绝，拦截成功，不再继续执行：一篇空白；
    }

    /**
     * @Description: 控制方法执行之后执行
     *  主要用于渲染公共数据：例如：菜单等信息

     * @CreateTime: 2022/10/11 8:47
     * @param: request
     * @param: response
     * @param: handler
     * @param: modelAndView
     **/
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("LoginInterceptor.postHandle....................... ");
    }

    /**
     * @Description: 页面中的视图、数据渲染完毕之后执行
     *  主要用于释放资源。
     * @Author: yang_yong
     * @CreateTime: 2022/10/11 8:47
     * @param: request
     * @param: response
     * @param: handler
     * @param: ex
     **/
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("LoginInterceptor.afterCompletion....................... ");
    }
}
